"use strict";

var router = require("router"),
    TokenService = require("router").TokenService,
    mongo = require('./core/mongoservice'),
    ObjectId = require('mongodb').ObjectID,
    Q = require('q');

function ResearchService() {
    console.log("ResearchService constructor");
}
ResearchService.prototype = Object.create(TokenService.prototype);
ResearchService.prototype.constructor = ResearchService;

ResearchService.prototype.getStartsWith = function (request, response, promise) {
    return promise.then(function (self) {
        //self.identify(request, response);
        var skip = parseInt(request.query.skip);
        var limit = parseInt(request.query.limit);

        var query = request.query.q;

        return self.mongoGetStartsWith(query, { skip: skip, limit: limit }).then(function (results) {
            return response.send({ request: request, content: results });
        });
    });
};

ResearchService.prototype.call = function (request, response, promise) {
    return promise.then(function (self) {

        var query = request.body.q;
        if (!query) throw new Error("Query is empty.");

        return self.mongoCall(query).then(function (results) {
            return response.send({ request: request, content: results });
        });
    });
};

/*-------------------------------------------------------*/
/*mongo daf*/

ResearchService.prototype.mongoGetStartsWith = function (query, options) {
    if (!query) throw new Error("query is not defined.");
    var self = this;

    options = options || {}
    var opts = {};
    if (options.limit) opts.limit = options.limit;
    if (options.skip) opts.skip = options.skip;
    opts.sort = { "reporting.call": -1, "reporting.put": -1, "value": 1 };

    query = query.replace(' ', '\\s');
    var regex = new RegExp("^" + query, "ig");

    return mongo.find('research', { value: { $regex: regex} }, opts).then(function (cursor) {
        return Q.ninvoke(cursor, 'toArray');
    });
};

ResearchService.prototype.mongoSave = function (value) {
    if (!value) throw new Error("value is not defined.");
    var self = this;

    value = value.toLowerCase();

    return mongo.findOne('research', { value: value }).then(function (item) {
        if (!item) return self.mongoInsert(value);
        else return self.mongoUpdate(value);
    });
};

ResearchService.prototype.mongoSaveList = function (values) {
    if (!values) throw new Error("values is not defined.");
    var self = this;

    var promises = [];
    values.forEach(function (value) {
        promises.push(self.mongoSave(value));
    });
    return Q.all(promises).then(function () {
        return values;
    });
};

ResearchService.prototype.mongoInsert = function (value) {
    if (!value) throw new Error("value is not defined.");
    var self = this;

    value = value.toLowerCase();

    var research = {
        value: value,
        reporting: {
            put: 1,
            call: 0
        }
    };

    return mongo.insert('research', research).then(function (data) {
        return data[0];
    });
};

ResearchService.prototype.mongoUpdate = function (value) {
    if (!value) throw new Error("value is not defined.");
    var self = this;

    value = value.toLowerCase();

    return mongo.update('research', { value: value }, { $inc: { "reporting.put": 1} });
};

ResearchService.prototype.mongoRemove = function (value) {
    if (!value) throw new Error("value is not defined.");
    var self = this;

    value = value.toLowerCase();

    return mongo.remove('research', { value: value });
};

ResearchService.prototype.mongoCall = function (query) {
    if (!query) throw new Error("query is not defined.");
    var self = this;

    query = query.replace(' ', '\\s');
    var regex = new RegExp(query, "ig");

    return mongo.update('research', { value: { $regex: regex} }, { $inc: { "reporting.call": 1} });
};

exports = module.exports = new ResearchService();